package rullekake.beans.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.MessageDigest;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

/**
 * Statisk klasse med hjelpemetoder
 *
 */
public class JsfUtil {

    /**
     * Formaterer List-lister til SelectedITems-lister for bruk i xhtml.
     * @param entities liste
     * @param selectOne ved true legges det til --- i toppen av lista.
     * @return selecteditems
     */
    public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
        int size = selectOne ? entities.size() + 1 : entities.size();
        SelectItem[] items = new SelectItem[size];
        int i = 0;
        if (selectOne) {
            items[0] = new SelectItem("", "---");
            i++;
        }
        for (Object x : entities) {
            items[i++] = new SelectItem(x, x.toString());
        }
        return items;
    }



    /**
     * Sender ut en gitt feilmelding til bruker
     *
     * @param msg
     */
    public static void addErrorMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString(msg),
                ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString(msg));
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);

    }

    /**
     * Sender ut en gitt infomelding til bruker
     * @param msg
     */
    public static void addSuccessMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO,
                ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString(msg),
                ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString(msg));
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }


    /**
     * Krypterer textstreng med SHA-256 kryptering
     * @param text
     * @return kryptertext som Base64
     */

    public static String encryptsha256(String text){
        byte[] digest = {};
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-256");
            md.update(text.getBytes("UTF-8"));
            digest = md.digest();

        } catch (Exception ex) {
        }
        return Base64.encode(digest);
        }


}